package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.gather.api.domain.ErpSellerProduct;
import com.erp.gather.domain.ErpSellerProductShare;
import com.ruoyi.gather.api.domain.ErpSellerProductExpand;
import com.ruoyi.gather.api.domain.ErpSellerProductSku;
import com.erp.gather.domain.bo.ErpSellerProductShareBo;
import com.erp.gather.domain.vo.ErpSellerProductShareVo;
import com.erp.gather.mapper.ErpSellerProductExpandMapper;
import com.erp.gather.mapper.ErpSellerProductMapper;
import com.erp.gather.mapper.ErpSellerProductShareMapper;
import com.erp.gather.mapper.ErpSellerProductSkuMapper;
import com.erp.gather.service.IErpSellerProductShareService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 个人商品分享Service业务层处理
 *
 * @author erp
 * @date 2023-11-16
 */
@RequiredArgsConstructor
@Service
public class ErpSellerProductShareServiceImpl implements IErpSellerProductShareService {

	private final ErpSellerProductShareMapper baseMapper;
	private final ErpSellerProductMapper sellerProductMapper;
	private final ErpSellerProductExpandMapper erpSellerProductExpandMapper;
	private final ErpSellerProductSkuMapper erpSellerProductSkuMapper;

	/**
	 * 查询个人商品分享
	 */
	@Override
	public ErpSellerProductShareVo queryById(Long id) {
		return baseMapper.selectVoById(id);
	}

	/**
	 * 查询个人商品分享列表
	 */
	@Override
	public TableDataInfo<ErpSellerProductShareVo> queryPageList(ErpSellerProductShareBo bo, PageQuery pageQuery) {
		LambdaQueryWrapper<ErpSellerProductShare> lqw = buildQueryWrapper(bo);
		Page<ErpSellerProductShareVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
		return TableDataInfo.build(result);
	}

	/**
	 * 查询个人商品分享列表
	 */
	@Override
	public List<ErpSellerProductShareVo> queryList(ErpSellerProductShareBo bo) {
		LambdaQueryWrapper<ErpSellerProductShare> lqw = buildQueryWrapper(bo);
		return baseMapper.selectVoList(lqw);
	}

	private LambdaQueryWrapper<ErpSellerProductShare> buildQueryWrapper(ErpSellerProductShareBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<ErpSellerProductShare> lqw = Wrappers.lambdaQuery();
		lqw.eq(bo.getUserId() != null, ErpSellerProductShare::getUserId, bo.getUserId());
		lqw.like(StringUtils.isNotBlank(bo.getShareName()), ErpSellerProductShare::getShareName, bo.getShareName());
		lqw.eq(StringUtils.isNotBlank(bo.getShareCode()), ErpSellerProductShare::getShareCode, bo.getShareCode());
		lqw.eq(StringUtils.isNotBlank(bo.getProducts()), ErpSellerProductShare::getProducts, bo.getProducts());
		lqw.eq(bo.getAddTime() != null, ErpSellerProductShare::getAddTime, bo.getAddTime());

		lqw.orderByDesc(ErpSellerProductShare::getAddTime);
		return lqw;
	}

	/**
	 * 新增个人商品分享
	 */
	@Override
	public R<Object> insertByBo(ErpSellerProductShareBo bo) {
		ErpSellerProductShare add = BeanUtil.toBean(bo, ErpSellerProductShare.class);
		validEntityBeforeSave(add);

		add.setAddTime(new Date());
		add.setUserId(SecurityUtils.getUserId());

		// 生成分享码

		boolean flag = baseMapper.insert(add) > 0;
		if (flag) {
			bo.setId(add.getId());
			return R.ok(add.getId());
		}
		return R.fail("生成失败");
	}

	/**
	 * 修改个人商品分享
	 */
	@Override
	public Boolean updateByBo(ErpSellerProductShareBo bo) {
		ErpSellerProductShare update = BeanUtil.toBean(bo, ErpSellerProductShare.class);
		validEntityBeforeSave(update);
		return baseMapper.updateById(update) > 0;
	}

	/**
	 * 保存前的数据校验
	 */
	private void validEntityBeforeSave(ErpSellerProductShare entity) {
		// TODO 做一些数据校验,如唯一约束
	}

	/**
	 * 批量删除个人商品分享
	 */
	@Override
	public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
		if (isValid) {
			// TODO 做一些业务上的校验,判断是否需要校验
		}
		return baseMapper.deleteBatchIds(ids) > 0;
	}

	@Override
	public R<Object> useShare(String shareCode) {
		// 获取分享的信息
//		ErpSellerProductShare collectProductShare = baseMapper.selectOne(
//				new LambdaQueryWrapper<ErpSellerProductShare>().eq(ErpSellerProductShare::getShareCode, shareCode));
		ErpSellerProductShare collectProductShare = baseMapper.selectById(shareCode);

		if (collectProductShare == null) {
			return R.fail("分享码不存在");
		}

		Long userId = SecurityUtils.getUserId();
//		Long userId = 1l;

		String products = collectProductShare.getProducts();
		List<String> productIds = Arrays.asList(products.split(","));
		//有问题
		List<ErpSellerProduct> sellerList = sellerProductMapper
				.selectList(new LambdaQueryWrapper<ErpSellerProduct>().in(ErpSellerProduct::getSellerId, productIds)
						.eq(ErpSellerProduct::getCreateBy, collectProductShare.getUserId()));
		for (ErpSellerProduct erpSellerProduct : sellerList) {

			Long sellerId = erpSellerProduct.getId();

			ErpSellerProduct newErpSellerProduct = new ErpSellerProduct();
			newErpSellerProduct = erpSellerProduct;
			newErpSellerProduct.setId(null);
			newErpSellerProduct.setSellerId(userId);
			newErpSellerProduct.setCreateBy(userId + "");
			newErpSellerProduct.setUpdateBy(userId + "");
			newErpSellerProduct.setCreateTime(null);
			newErpSellerProduct.setUpdateTime(null);
			sellerProductMapper.insert(newErpSellerProduct);

			Long newSellerId = newErpSellerProduct.getId();

			// 保存扩展类
			ErpSellerProductExpand productExpand = erpSellerProductExpandMapper
					.selectOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
							.eq(ErpSellerProductExpand::getSellerProductId, sellerId));

			ErpSellerProductExpand newProductExpand = new ErpSellerProductExpand();
			newProductExpand = productExpand;
			newProductExpand.setId(null);
			newProductExpand.setSellerProductId(newSellerId);
			newProductExpand.setCreateBy(userId + "");
			newProductExpand.setUpdateBy(userId + "");
			newProductExpand.setCreateTime(null);
			newProductExpand.setUpdateTime(null);
			erpSellerProductExpandMapper.insert(newProductExpand);

			List<ErpSellerProductSku> productSkus = erpSellerProductSkuMapper
					.selectList(new LambdaQueryWrapper<ErpSellerProductSku>()
							.eq(ErpSellerProductSku::getSellerProductId, sellerId));
			List<ErpSellerProductSku> resList = new ArrayList<>();
			for (ErpSellerProductSku sku : productSkus) {
				ErpSellerProductSku newSku = new ErpSellerProductSku();
				newSku = sku;
				newSku.setId(null);
				newSku.setSellerProductId(newSellerId);
				newSku.setCreateBy(userId + "");
				newSku.setUpdateBy(userId + "");
				newSku.setCreateTime(null);
				newSku.setUpdateTime(null);
				resList.add(newSku);
			}
			erpSellerProductSkuMapper.insertBatch(resList);
		}

		return R.ok("激活码使用成功");
	}
}
